//
//  NewTask.m
//  RRQS
//
//  Created by kyjun on 16/3/23.
//
//

#import "NewTask.h"
#import "TaskHeader.h"
#import "TaskCell.h"
#import "NewTaskFooter.h"
#import "MOrder.h"
#import <DZNEmptyDataSet/UIScrollView+EmptyDataSet.h>
#import "WJWaiMaiDodel.h"
#define wmCount self.listDataMarray.count

@interface NewTask ()<NewTaskFooterDelegate,DZNEmptyDataSetDelegate,DZNEmptyDataSetSource,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>

@property(nonatomic,strong) UICollectionView* collectionView;
@property(nonatomic,strong) NSMutableArray* arrayData;

@property(nonatomic,strong) UIView* bottomView;
@property(nonatomic,strong) UIButton* btnRefreshData;

@property(nonatomic,strong) NSString* cellIdentifier;
@property(nonatomic,strong) NSString* headerIdentifier;
@property(nonatomic,strong) NSString* footerIdentifier;

@property (nonatomic, strong) WJWaiMaiDodel *waiMaiDodel; // 数据源.item
@property (nonatomic, strong) NSMutableArray *listDataMarray; // 外卖数据源
@property (nonatomic, strong) NSMutableArray *hlistDataMarray; // 跑腿数据源
@property (nonatomic, assign) NSInteger totalCountInteger; // 总数
@end

@implementation NewTask
// 请求界面数据源
-(void)queryData{
    if(self.Identity.locationInfo.enabled){
        AFHTTPRequestOperationManager* mgr = [AFHTTPRequestOperationManager manager];
        NSDictionary* arg = @{@"ince":@"get_rr_help_order_list",@"lat":self.Identity.locationInfo.lat,@"lng":self.Identity.locationInfo.lng};
        [mgr POST:kHost parameters:arg success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
            [WMHelper outPutJsonString:responseObject];
            NSInteger flag = [[responseObject objectForKey:@"status"]integerValue];
            if(flag == 1){
                [self.listDataMarray removeAllObjects];
                [self.hlistDataMarray removeAllObjects];
                self.waiMaiDodel = [WJWaiMaiDodel yy_modelWithDictionary:responseObject];
                [self.listDataMarray addObjectsFromArray:self.waiMaiDodel.list];
                [self.hlistDataMarray addObjectsFromArray:self.waiMaiDodel.hlist];
                
                if ([WMHelper isNULLOrnil:self.listDataMarray]) {
                    if ([WMHelper isNULLOrnil:self.hlistDataMarray]) {
                        self.totalCountInteger = 0;
                    }else{
                        self.totalCountInteger = self.hlistDataMarray.count;
                    }
                }
                if ([WMHelper isNULLOrnil:self.hlistDataMarray]) {
                    if ([WMHelper isNULLOrnil:self.listDataMarray]) {
                        self.totalCountInteger = 0;
                    }else{
                        self.totalCountInteger = self.listDataMarray.count;
                    }
                }
                if (![WMHelper isNULLOrnil:self.listDataMarray] && ![WMHelper isNULLOrnil:self.hlistDataMarray]) {
                    self.totalCountInteger = self.listDataMarray.count + self.hlistDataMarray.count;
                }
                [self.collectionView reloadData];
            }else{
                [self alertHUD:[responseObject objectForKey:@"fail"]];
            }
            [self.collectionView.mj_header endRefreshing];
        } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
            [self alertHUD:@"网络异常"];
            [self.collectionView.mj_header endRefreshing];
        }];
    }else{
        [self.collectionView.mj_header endRefreshing];
        [[NSNotificationCenter defaultCenter] postNotificationName:NotificationToLocationService object:nil];
    }
    
}
// 帮你买 帮你卖 帮你取 提交
- (void)newsTaskCommitToServerWithStr:(NSString *)typeStr orderIdStr:(NSString *)orderid
{
    self.HUD = [[MBProgressHUD alloc] initWithView:self.view.window];
    [self.view.window addSubview:self.HUD];
    self.HUD.delegate = self;
    self.HUD.minSize = CGSizeMake(135.f, 135.f);
    [self.HUD setLabelFont:[UIFont systemFontOfSize:14.f]];
    [self.HUD show:YES];
    AFHTTPRequestOperationManager* mgr = [AFHTTPRequestOperationManager manager];
    NSDictionary* arg = @{@"ince":@"qs_qiang",@"emp_id":self.Identity.userInfo.userID,@"order_id":orderid,@"type":typeStr};
    [mgr POST:kHost parameters:arg success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        [WMHelper outPutJsonString:responseObject];
        NSInteger flag = [[responseObject objectForKey:@"status"]integerValue];
        if(flag == 1){
            [self hidHUD:@"成功" success:YES];
            [[NSNotificationCenter defaultCenter]postNotificationName:NotificationHomeRefreshing object:nil];
            [[NSNotificationCenter defaultCenter]postNotificationName:NotificationGrabOrderRefreshWaitOrder object:nil];
        }else{
            NSLog(@"%@",[responseObject objectForKey:@"fail"]);
            [self hidHUD:[responseObject objectForKey:@"fail"]];
        }
        [self.collectionView.mj_header beginRefreshing];
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        NSLog(@"%@",error.description);
        [self hidHUD:@"网络异常"];
    }];
}
// 抢单
- (void)newsTaskGetOrderCommitToServerWithOrderIdStr:(NSString *)orderid
{
    self.HUD = [[MBProgressHUD alloc] initWithView:self.view.window];
    [self.view.window addSubview:self.HUD];
    self.HUD.delegate = self;
    self.HUD.minSize = CGSizeMake(135.f, 135.f);
    [self.HUD setLabelFont:[UIFont systemFontOfSize:14.f]];
    [self.HUD show:YES];
    AFHTTPRequestOperationManager* mgr = [AFHTTPRequestOperationManager manager];
    NSDictionary* arg = @{@"ince":@"qs_qiang_new",@"emp_id":self.Identity.userInfo.userID,@"main_id":orderid};
    [mgr POST:kHost parameters:arg success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        [WMHelper outPutJsonString:responseObject];
        NSInteger flag = [[responseObject objectForKey:@"status"]integerValue];
        if(flag == 1){
            [self hidHUD:@"成功" success:YES];
            [[NSNotificationCenter defaultCenter]postNotificationName:NotificationHomeRefreshing object:nil];
            [[NSNotificationCenter defaultCenter]postNotificationName:NotificationGrabOrderRefreshWaitOrder object:nil];
        }else{
            NSLog(@"%@",[responseObject objectForKey:@"fail"]);
            [self hidHUD:[responseObject objectForKey:@"fail"]];
        }
        [self.collectionView.mj_header beginRefreshing];
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        NSLog(@"%@",error.description);
        [self hidHUD:@"网络异常"];
    }];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.cellIdentifier = @"NewTaskCell";
    self.headerIdentifier = @"NewTaskHeader";
    self.footerIdentifier = @"NewTaskFooter";
    [self layoutUI];
    [self layoutConstraints];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshData:) name:NotificationRemoteAt object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshData:) name:NotificationRefreshNewTask object:nil];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if(self.Identity.userInfo.isLogin){
        [self refereshDatasource];
    }
}
#pragma mark =====================================================  user interface layout
-(void)layoutUI{
    [self.view addSubview:self.bottomView];
    [self.bottomView addSubview:self.btnRefreshData];
    
    UICollectionViewFlowLayout* blockLayout = [[UICollectionViewFlowLayout alloc]init];
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:blockLayout];
    self.collectionView.backgroundColor = [UIColor clearColor];
    self.collectionView.bounces = YES;
    self.collectionView.alwaysBounceVertical = YES;
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    [self.view addSubview:self.collectionView];
    [self.collectionView registerClass:[TaskCell class] forCellWithReuseIdentifier:NSStringFromClass([TaskCell class])];
    
    [self.collectionView registerClass:[TaskHeader class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:self.headerIdentifier];
    [self.collectionView registerClass:[NewTaskFooter class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:self.footerIdentifier];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.collectionView.emptyDataSetDelegate = self;
    self.collectionView.emptyDataSetSource = self;
}
-(void)layoutConstraints{
    self.bottomView.translatesAutoresizingMaskIntoConstraints = NO;
    self.btnRefreshData.translatesAutoresizingMaskIntoConstraints = NO;
    self.collectionView.translatesAutoresizingMaskIntoConstraints = NO;
    
    [self.bottomView addConstraint:[NSLayoutConstraint constraintWithItem:self.bottomView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:50.f]];
    [self.bottomView addConstraint:[NSLayoutConstraint constraintWithItem:self.bottomView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:SCREEN_WIDTH]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.bottomView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0.f]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.bottomView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0.f]];
    
    [self.bottomView addConstraint:[NSLayoutConstraint constraintWithItem:self.btnRefreshData attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.bottomView attribute:NSLayoutAttributeTop multiplier:1.0 constant:5.f]];
    [self.bottomView addConstraint:[NSLayoutConstraint constraintWithItem:self.btnRefreshData attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.bottomView attribute:NSLayoutAttributeLeft multiplier:1.0 constant:5.f]];
    [self.bottomView addConstraint:[NSLayoutConstraint constraintWithItem:self.btnRefreshData attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.bottomView attribute:NSLayoutAttributeRight multiplier:1.0 constant:-5.f]];
    [self.bottomView addConstraint:[NSLayoutConstraint constraintWithItem:self.btnRefreshData attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.bottomView attribute:NSLayoutAttributeBottom multiplier:1.0 constant:-5.f]];
    
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.collectionView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0 constant:0.f]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.collectionView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0.f]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.collectionView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeRight multiplier:1.0 constant:0.f]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.collectionView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.bottomView attribute:NSLayoutAttributeTop multiplier:1.0 constant:0.f]];
}
-(void)refereshDatasource{
    __weak typeof(self) weakSelf = self;
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf queryData];
    }];
    [self.collectionView.mj_header beginRefreshing];
}
#pragma mark =====================================================  <UICollectionViewDataSource>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 1;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    TaskCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([TaskCell class]) forIndexPath:indexPath];
    if (![WMHelper isNULLOrnil:self.listDataMarray]) { // 如果数组不为空
        if (indexPath.section < self.listDataMarray.count) {
            cell.waiMaiDodelListitems = ((WJWaiMaiDodelList *)self.listDataMarray[indexPath.section]).items[0];
        }else{
            cell.waiMaiDodelHList = self.hlistDataMarray[indexPath.section - wmCount];
        }
    }else{// 没有跑腿 self.listDataMarray数组为空的时候
        cell.waiMaiDodelHList = self.hlistDataMarray[indexPath.section];
    }
    
    return cell;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return self.totalCountInteger;
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if([kind isEqualToString:UICollectionElementKindSectionHeader]){
        UICollectionReusableView  *reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:self.headerIdentifier forIndexPath:indexPath];
        TaskHeader *header = (TaskHeader *) reusableView;
        if (indexPath.section < self.listDataMarray.count) {
            header.waiMaiDodelList = self.listDataMarray[indexPath.section];
        }else{
            header.waiMaiDodelHList = self.hlistDataMarray[indexPath.section - wmCount];
        }
        return reusableView;
    }else if ([kind isEqualToString:UICollectionElementKindSectionFooter]){
        UICollectionReusableView  *reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:self.footerIdentifier forIndexPath:indexPath];
        NewTaskFooter *footer = (NewTaskFooter *) reusableView;
        footer.delegate = self;
        if (indexPath.section < self.listDataMarray.count) {
            footer.waiMaiDodelList = self.listDataMarray[indexPath.section];
        }else{
            footer.waiMaiDodelHList = self.hlistDataMarray[indexPath.section - wmCount];
        }
        
        return reusableView;
    }
    return nil;
}

#pragma mark =====================================================  <UICollectionViewDelegate>
#pragma mark =====================================================  <UICollectionViewDelegateFlowLayout>
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(SCREEN_WIDTH, 60);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(SCREEN_WIDTH, 75);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
//    MOrder* empty = self.arrayData[section];
//    MSubOrder* item = (MSubOrder*)[empty.arraySubOrder firstObject];
//    if([WMHelper isEmptyOrNULLOrnil:item.phoneAddress]){
//        return CGSizeMake(SCREEN_WIDTH, 120);
//    }
    return CGSizeMake(SCREEN_WIDTH, 150);
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    
    return UIEdgeInsetsMake(0.f, 0.f, 0.f, 0.f);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    
    return 0.f; /// 行与行之间的间隔距离
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0.f; //相邻两个 item 间距
}

#pragma mark =====================================================  <DZNEmptyDataSetDelegate> 协议实现
#pragma mark =====================================================  <DZNEmptyDataSetSource> 协议实现

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
{
    return [[NSAttributedString alloc] initWithString:@"附近暂时没有任务" attributes:@{NSFontAttributeName :[UIFont boldSystemFontOfSize:17.0],NSForegroundColorAttributeName:[UIColor colorWithRed:131/255.f green:131/255.f blue:131/255.f alpha:1.0]}];
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
{
    return [UIImage imageNamed:@"order_null"];
}

- (NSAttributedString *)buttonTitleForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state
{
    NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
    // paragraph.lineBreakMode = NSLineBreakByWordWrapping;
    paragraph.alignment = NSTextAlignmentCenter;
    return  [[NSMutableAttributedString alloc] initWithString:@"休息一会\"刷新列表\"试试" attributes:@{NSForegroundColorAttributeName:[UIColor colorWithRed:191/255.f green:191/255.f blue:191/255.f alpha:1.0],NSParagraphStyleAttributeName:paragraph,NSFontAttributeName:[UIFont boldSystemFontOfSize:15.f]}];
}

- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView
{
    return roundf(self.collectionView.frame.size.height/10.0);
}
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
{
    return YES;
}
#pragma mark =====================================================  <NewTaskFooterDelegate>
- (void)NewTaskPaoTui:(WJWaiMaiDodelHList *)wMaiDodelHList // 跑腿 提交按钮 代理方法
{
    NSLog(@"跑腿");
    NSString *typeStr = @"";
    if ([wMaiDodelHList.type isEqualToString:@"buy"]) {
        typeStr = @"1";
    }
    if ([wMaiDodelHList.type isEqualToString:@"send"]) {
        typeStr = @"2";
    }
    if ([wMaiDodelHList.type isEqualToString:@"get"]) {
        typeStr = @"3";
    }
    [self newsTaskCommitToServerWithStr:typeStr orderIdStr:wMaiDodelHList.order_id];
}
- (void)NewTaskWaiMai:(WJWaiMaiDodelList *)wMaiDodelList
{
    NSLog(@"外卖");
    WJWaiMaiDodelListitems *item = wMaiDodelList.items[0];
    [self newsTaskGetOrderCommitToServerWithOrderIdStr:item.order_id];
}
#pragma mark =====================================================  SEL
-(IBAction)reloadData:(UIButton*)sender{
        [self.collectionView.mj_header beginRefreshing];
}

#pragma mark =====================================================  Notification
-(void)refreshData:(NSNotification*)notification{
        [self.collectionView.mj_header beginRefreshing];
}

#pragma mark =====================================================  property package
-(NSMutableArray *)arrayData{
    if(!_arrayData){
        _arrayData = [[NSMutableArray alloc]init];
    }
    return _arrayData;
}

-(UIView *)bottomView{
    if(!_bottomView){
        _bottomView = [[UIView alloc]init];
        CALayer* border = [[CALayer alloc]init];
        border.frame = CGRectMake(0.f, 0, SCREEN_WIDTH, 0.5f);
        border.backgroundColor = [UIColor colorWithRed:242/255.f green:242/255.f blue:242/255.f alpha:1.0].CGColor;
        [_bottomView.layer addSublayer:border];
        
    }
    return _bottomView;
}

-(UIButton *)btnRefreshData{
    if(!_btnRefreshData){
        _btnRefreshData = [UIButton buttonWithType:UIButtonTypeCustom];
        _btnRefreshData.backgroundColor = [UIColor colorWithRed:248/255.f green:159/255.f blue:39/255.f alpha:1.0];
        [_btnRefreshData setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_btnRefreshData setTitle:@"刷新列表" forState:UIControlStateNormal];
        [_btnRefreshData addTarget:self action:@selector(reloadData:) forControlEvents:UIControlEventTouchUpInside];
        _btnRefreshData.layer.masksToBounds = YES;
        _btnRefreshData.layer.cornerRadius = 5.f;
        _btnRefreshData.layer.borderColor = [UIColor colorWithRed:231/255.f green:231/255.f blue:231/255.f alpha:1.0].CGColor;
    }
    return _btnRefreshData;
}
- (NSMutableArray *)listDataMarray
{
    if (!_listDataMarray) {
        _listDataMarray = @[].mutableCopy;
    }
    return _listDataMarray;
}
- (NSMutableArray *)hlistDataMarray
{
    if (!_hlistDataMarray) {
        _hlistDataMarray = @[].mutableCopy;
    }
    return _hlistDataMarray;
}


@end
